import mcpIcon from "@lobehub/icons-static-svg/icons/mcp.svg";
import { ButtonWithTooltip } from "@renderer/components/business/button-with-tooltip";
import { McpServerSelectModal } from "@renderer/components/business/mcp-server-select-modal";
import { cn } from "@renderer/lib/utils";
import { useEnabledOrderedMcpServers } from "@renderer/queries/hooks/use-mcp-servers";
import { useMemo, useState } from "react";
import { useTranslation } from "react-i18next";

interface McpServerSelectProps {
  selectedServerIds: string[];
  onSelectionChange: (serverIds: string[]) => void;
  disabled?: boolean;
}

export function McpServerSelect({
  selectedServerIds,
  onSelectionChange,
  disabled = false,
}: McpServerSelectProps) {
  const { t } = useTranslation("translation", {
    keyPrefix: "chat.tool-bar",
  });

  const [isOpen, setIsOpen] = useState(false);
  const { data: mcpServers = [] } = useEnabledOrderedMcpServers();

  // Get selected servers info
  const selectedServers = useMemo(() => {
    return mcpServers.filter((server) => selectedServerIds.includes(server.id));
  }, [mcpServers, selectedServerIds]);

  const hasSelectedServers = selectedServers.length > 0;

  const displayText = useMemo(() => {
    if (selectedServers.length === 0) {
      return t("mcp-server-select-placeholder");
    }
    if (selectedServers.length === 1) {
      return selectedServers[0].name;
    }
    return t("mcp-servers-selected", { count: selectedServers.length });
  }, [selectedServers, t]);

  const tooltipText = useMemo(() => {
    if (disabled) return t("disabled");
    if (selectedServers.length === 0) {
      return t("mcp-server-select-placeholder");
    }
    return displayText;
  }, [disabled, selectedServers.length, displayText, t]);

  // Show nothing if no MCP servers available
  if (mcpServers.length === 0) {
    return null;
  }

  return (
    <div className="relative">
      <ButtonWithTooltip
        className={cn(
          hasSelectedServers && "bg-primary/15 text-primary",
          disabled && "cursor-not-allowed opacity-50",
        )}
        title={tooltipText}
        onClick={() => setIsOpen(!isOpen)}
        isDisabled={disabled}
      >
        <img
          src={mcpIcon}
          alt="MCP"
          className={cn(
            "size-4 transition-opacity",
            hasSelectedServers
              ? "[filter:brightness(0)_saturate(100%)_invert(0.2)] dark:[filter:brightness(0)_saturate(100%)_invert(0.8)]"
              : "[filter:brightness(0)_saturate(100%)_invert(0.6)] dark:[filter:brightness(0)_saturate(100%)_invert(0.7)]",
          )}
        />
      </ButtonWithTooltip>

      <McpServerSelectModal
        isOpen={isOpen}
        onOpenChange={setIsOpen}
        selectedServerIds={selectedServerIds}
        onSelectionChange={onSelectionChange}
        mcpServers={mcpServers}
      />
    </div>
  );
}
